package ru.urfc.portal.ui.client;

import com.extjs.gxt.ui.client.data.ModelData;

import ru.urfc.portal.ui.client.controllers.ItemsController;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;
import ru.urfc.portal.ui.client.descriptor.GridField;
import ru.urfc.portal.ui.client.model.catalogs.DocumentState;
import ru.urfc.portal.ui.client.widgets.AttachedFiles;
import ru.urfc.portal.ui.client.widgets.DocumentHeader;
import ru.urfc.portal.ui.client.widgets.SelectDevices;

public abstract class BaseDocument extends BaseGooglet {

	private ItemsController controller;
	private GridField stateCodeField;
	private GridField idsField;
	private DocumentHeader header;
	private AttachedFiles attachedFiles;
	private SelectDevices selectDevices;
	
	@Override
	protected void init() {
		GridDescriptor descriptor = header.getDescriptor();
		descriptor.setSpecialRestUrl("POST", CLIENTS, getClientId(), DOCUMENTS, getItemId(), DOCUMENT_SUBMIT);
		stateCodeField = descriptor.addField("state/code");
		idsField = descriptor.addField("deviceIds").setEditable();

		init(descriptor);
		controller = createController(descriptor);
		if (attachedFiles != null) {
			attachedFiles.init(this);
		}
		if (selectDevices != null) {
			selectDevices.init(this, getClientId(), getItemId());
		}
	}
	
	protected abstract void init(GridDescriptor descriptor);
	
	protected void bind(AttachedFiles attachedFiles) {
		this.attachedFiles = attachedFiles;
	}

	protected void bind(SelectDevices selectDevices) {
		this.selectDevices = selectDevices;
	}	

	public void setHeader(DocumentHeader header) {
		this.header = header;
	}
	
	public ItemsController getController() {
		return controller;
	}
	
	public GridField getStateCodeField() {
		return stateCodeField;
	}
	
	public GridField getIdsField() {
		return idsField;
	}

	public String getStateCode() {
		ModelData modelData = controller.getModelData();
		return stateCodeField.getValue(modelData);
	}

	public boolean isDraft() {
		return getStateCode().equals(DocumentState.DRAFT.getCode());
	}
	
}
